import { logoutApi } from "@/api/modules/login";
import { editUser, getUser, modifyUserPassWord, saveLogo } from "@/api/modules/user";
import AutoSaveInput from "@/components/Frame/auto-save-input";
import { LOGIN_URL } from "@/config/config";
import { changeUserInfo } from "@/hooks/useUserData";
import "@/layouts/components/ThemeDrawer/index.scss";
import { GlobalStore } from "@/stores";
import { AuthStore } from "@/stores/modules/auth";
import { showTips } from "@/utils/util";
import { CircleCheckFilled, Edit, Lock } from "@element-plus/icons-vue";
import { ElForm, ElMessageBox } from "element-plus";
import { defineComponent, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import UserDetailDialog from "./../components/form.vue";
import "./user-profile.scss";
import logo from "@/assets/images/logo.png";

export default defineComponent({
	setup() {
		return () => {
			return (
				<div class="user-profile">
					<div class="flex">
						<div class="flex-row w-1/3 mr-4 bg-white">
							<BasicInfo class="bg-white p-8 " />
							<PwdInfo class="bg-white p-8" />
						</div>

						<div class="flex-1">
							<SystemInfo class="bg-white p-8" />
							<LayoutInfo class="bg-white p-8 mt-4" />
						</div>
					</div>
				</div>
			);
		};
	}
});

const BasicInfo = defineComponent({
	setup() {
		const globalStore = GlobalStore();
		const userInfo = ref<any>({});
		initUser();

		const EmailInputRef = ref<any>();
		const MobileInputRef = ref<any>();
		const saveUserField = async (target: "email" | "mobile") => {
			let value;
			if (target == "email") {
				value = userInfo.value.email;
				EmailInputRef.value.unFocus();
			} else if (target == "mobile") {
				value = userInfo.value.mobile;
				MobileInputRef.value.unFocus();
			} else {
				return;
			}
			await changeUserInfo(target, value);
		};
		async function initUser() {
			let { result } = await getUser(globalStore.userInfo.username);
			userInfo.value = result || {};
		}
		// 打开 drawer(新增、查看、编辑)
		const drawerRef = ref();
		const openDrawer = () => {
			let params = {
				title: "编辑个人信息",
				rowData: { ...userInfo.value },
				api: editUser
			};
			drawerRef.value.acceptParams(params);
		};
		return () => {
			return (
				<div class="user-profile">
					<UserDetailDialog class="user-profile-dialog" ref={drawerRef} width="600px" />
					<div class="group-title font-bold pb-3 mb-2 border-b-2 flex justify-between">
						基本信息
						<el-link type="primary" icon={Edit} onClick={() => openDrawer()}>
							编辑
						</el-link>
					</div>
					<el-form label-width="80px" class="user-basic-info pt-4" size="small">
						<el-form-item label="用户名：">
							{userInfo.value.username}
							{userInfo.value.alias ? `（${userInfo.value.alias}）` : ""}
						</el-form-item>
						<el-form-item label="状态：">
							{userInfo.value.status == "0" && <el-tag type="danger">停用</el-tag>}
							{userInfo.value.status == "1" && <el-tag type="success">启用</el-tag>}
							{!userInfo.value.status && <el-tag type="danger">停用</el-tag>}
						</el-form-item>
						<el-form-item label="Email：">
							<div class="flex justify-between w-full">
								<AutoSaveInput
									ref={EmailInputRef}
									v-model={userInfo.value.email}
									placeholder="请输入Email"
									onChange={() => saveUserField("email")}
								/>
							</div>
						</el-form-item>
						<el-form-item label="手机号：">
							<div class="flex justify-between w-full">
								<AutoSaveInput
									ref={MobileInputRef}
									v-model={userInfo.value.mobile}
									placeholder="请输入手机号"
									onChange={() => saveUserField("mobile")}
								/>
							</div>
						</el-form-item>
						<el-form-item label="角色：">{userInfo.value.roleName || "--"}</el-form-item>
						<el-form-item label="公司：">{userInfo.value.company || "--"}</el-form-item>
						<el-form-item label="分组：">
							<el-tooltip show-after={500} content={userInfo.value.deptName}>
								<div class="truncate">{userInfo.value.deptName || "--"}</div>
							</el-tooltip>
						</el-form-item>
						<el-form-item label="有效期：">
							{userInfo.value.tokenExp ? userInfo.value.tokenExp / 24 / 60 / 60 / 1000 : "--"}
						</el-form-item>
					</el-form>
				</div>
			);
		};
	}
});

interface PasswordForm {
	oldPwd: string;
	newPwd: string;
	confirmPwd: string;
}
const PwdInfo = defineComponent({
	setup() {
		const loading = ref(false);
		const { userInfo, setToken } = GlobalStore();
		const router = useRouter();
		const pwdForm = reactive<PasswordForm>({ oldPwd: "", newPwd: "", confirmPwd: "" });
		const validatePass = (rule: any, value: any, callback: any) => {
			if (value === "") {
				callback(new Error("请确认密码"));
			} else if (value !== pwdForm.newPwd) {
				callback(new Error("两次输入不一致"));
			} else {
				callback();
			}
		};
		const formRules = reactive({
			oldPwd: [{ required: true, message: "请输入旧密码", trigger: "change" }],
			newPwd: [{ required: true, message: "请确认新密码", trigger: "change" }],
			confirmPwd: [{ required: true, trigger: "blur", validator: validatePass }]
		});
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const changePwd = () => {
			formRef.value?.validate(async valid => {
				if (!valid) return;
				// let { success, message } = await checkUserPassWord({ username: userInfo.username, password: pwdForm.oldPwd });
				// if (!success) {
				// 	ElMessage.error({ message: message });
				// 	return;
				// }
				let { code } = await modifyUserPassWord({
					username: userInfo.username,
					password: pwdForm.oldPwd,
					newPassword: pwdForm.newPwd
				});
				let ok = showTips(code, "修改密码");
				if (ok) {
					pwdForm.oldPwd = "";
					pwdForm.newPwd = "";
					pwdForm.confirmPwd = "";
					formRef.value?.resetFields();
					ElMessageBox.confirm("您是否确认退出登录?", "温馨提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					}).then(async () => {
						const authStore = AuthStore();
						authStore.setDeptList([]);
						// 1.调用退出登录接口
						await logoutApi();
						// 2.清除 Token
						setToken("");
						// 3.重定向到登陆页
						router.replace(LOGIN_URL);
					});
				}
			});
		};
		return () => {
			return (
				<div class="">
					<div class="group-title font-bold pt-4 pb-3 mb-7 border-b-2">修改密码</div>
					<el-form model={pwdForm} ref={formRef} rules={formRules} label-width="80px">
						<el-form-item prop="oldPwd" label="旧密码">
							<el-input v-model={pwdForm.oldPwd} placeholder="请输入旧密码" type="password">
								{{
									prefix: () => {
										return (
											<el-icon class="el-input__icon">
												<Lock />
											</el-icon>
										);
									}
								}}
							</el-input>
						</el-form-item>
						<el-form-item prop="newPwd" label="新密码">
							<el-input v-model={pwdForm.newPwd} placeholder="请输入新密码" type="password">
								{{
									prefix: () => {
										return (
											<el-icon class="el-input__icon">
												<Lock />
											</el-icon>
										);
									}
								}}
							</el-input>
						</el-form-item>
						<el-form-item prop="confirmPwd" label="确认密码">
							<el-input v-model={pwdForm.confirmPwd} placeholder="请确认新密码" type="password">
								{{
									prefix: () => {
										return (
											<el-icon class="el-input__icon">
												<Lock />
											</el-icon>
										);
									}
								}}
							</el-input>
						</el-form-item>
					</el-form>
					<div class="flex justify-end">
						<el-button class="" onClick={changePwd} type="primary" loading={loading.value}>
							确定
						</el-button>
					</div>
				</div>
			);
		};
	}
});
const SystemInfo = defineComponent({
	setup() {
		const globalStore = GlobalStore();
		const custForm = reactive({
			systemName: globalStore.systemName,
			logo: globalStore.themeConfig.logo
		});
		const uploadSuccess = (res: any) => {
			custForm.logo = res.result;
		};
		const isDisabled = ref(globalStore.userInfo.creatorId != "1");
		const clickSave = async () => {
			custForm.logo = !custForm.logo || custForm.logo == logo ? "" : custForm.logo;
			let { code } = await saveLogo(custForm);
			let ok = showTips(code, "个性化设置");
			if (ok) {
				globalStore.setLogo(custForm.logo);
				globalStore.setSystemName(custForm.systemName);
			}
		};
		return () => {
			return (
				<div>
					<div class="group-title font-bold pb-3 mb-4 border-b-2">个性化设置</div>
					<el-form label-width="120px" size="large" class="pt-3">
						<el-form-item label="系统名称：">
							<div class="flex w-full">
								<el-input v-model={custForm.systemName} class="flex-1" />
								<el-upload
									show-file-list={false}
									on-success={uploadSuccess}
									headers={{
										Authentication: globalStore.token,
										systemid: globalStore.systemid,
										timestamp: Date.now()
									}}
									action="/api/file/upload"
								>
									<el-button type="primary" plain disabled={isDisabled.value}>
										上传Logo
									</el-button>
								</el-upload>
							</div>
						</el-form-item>
						<el-form-item label="实时预览：" class="preview">
							<div class="system-title-preview flex pl-5">
								<el-image src={!custForm.logo || custForm.logo == logo ? logo : `/api/file/download/${custForm.logo}`}></el-image>
								<div class="title ">{custForm.systemName}</div>
							</div>
							<div class="pt-2">
								<el-button type="primary" plain size="default" disabled={isDisabled.value} onClick={clickSave}>
									确定
								</el-button>
								<el-button
									size="default"
									disabled={isDisabled.value}
									onClick={() => {
										globalStore.setLogo("");
										globalStore.setSystemName("");
										custForm.systemName = globalStore.systemName;
										custForm.logo = globalStore.themeConfig.logo;
										clickSave();
									}}
								>
									重置
								</el-button>
							</div>
						</el-form-item>
						<el-form-item label="内容提示：">
							<div class="text-gray-500 leading-6 pt-1">
								<div>1.显示方式为系统logo+系统名称</div>
								<div>2.logo的高度为30，将以高度为基准等比缩放</div>
								<div>3.图片格式为png</div>
								<div>4.图片大小不能超过2M</div>
							</div>
						</el-form-item>
					</el-form>
				</div>
			);
		};
	}
});
const LayoutInfo = defineComponent({
	setup() {
		const globalStore = GlobalStore();
		const themeConfig = computed(() => globalStore.themeConfig);

		// 切换布局方式
		const changeLayout = (val: string) => {
			globalStore.setThemeConfig({ ...themeConfig.value, layout: val });
		};
		return () => {
			return (
				<div class="layout-settting">
					<div class="group-title font-bold pb-3 mb-4 border-b-2">个性化布局</div>
					<div class="layout-box">
						<div class="grid md:grid-cols-3 gap-4 text-center w-full">
							<div class="hidden">
								<div
									class={`layout-item layout-vertical ${themeConfig.value.layout == "vertical" ? "is-active" : ""} m-auto`}
									onClick={() => changeLayout("vertical")}
								>
									<div class="layout-dark">
										<div class="layout-light h-4"></div>
									</div>
									<div class="layout-container">
										<div class="layout-light"></div>
										<div class="layout-content"></div>
									</div>
									<el-icon v-show={themeConfig.value.layout == "vertical"}>
										<CircleCheckFilled />
									</el-icon>
								</div>
								<div class="text-sm text-gray-700">纵向</div>
							</div>
							<div>
								<div
									class={`layout-item layout-transverse ${themeConfig.value.layout == "transverse" ? "is-active" : ""} m-auto`}
									onClick={() => {
										changeLayout("transverse");
									}}
								>
									<div class="layout-dark"></div>
									<div class="layout-content"></div>
									<el-icon v-show={themeConfig.value.layout == "transverse"}>
										<CircleCheckFilled />
									</el-icon>
								</div>
								<div class="text-sm text-gray-700">横向</div>
							</div>
							<div>
								<div
									class={`layout-item layout-classic ${themeConfig.value.layout == "three" ? "is-active" : ""} m-auto`}
									onClick={() => changeLayout("three")}
								>
									<div class="layout-dark"></div>
									<div class="layout-container">
										<div class="layout-light"></div>
										<div class="layout-content"></div>
									</div>
									<el-icon v-show={themeConfig.value.layout == "three"}>
										<CircleCheckFilled />
									</el-icon>
								</div>
								<div class="text-sm text-gray-700">三级菜单</div>
							</div>
							<div>
								<div
									class={`layout-item layout-columns ${themeConfig.value.layout == "columns" ? "is-active" : ""} m-auto`}
									onClick={() => changeLayout("columns")}
								>
									<div class="layout-dark"></div>
									<div class="layout-light"></div>
									<div class="layout-content"></div>
									<el-icon v-show={themeConfig.value.layout == "columns"}>
										<CircleCheckFilled />
									</el-icon>
								</div>
								<div class="text-sm text-gray-700">分栏</div>
							</div>
						</div>
					</div>
				</div>
			);
		};
	}
});
